package tx.jdbc;

import cn.stimd.spring.beans.MutablePropertyValues;
import cn.stimd.spring.beans.factory.annotation.Value;
import cn.stimd.spring.context.annotation.Bean;
import cn.stimd.spring.context.annotation.ComponentScan;
import cn.stimd.spring.context.annotation.Configuration;
import cn.stimd.spring.context.annotation.PropertySource;
import cn.stimd.spring.jdbc.core.JdbcTemplate;
import cn.stimd.spring.validation.DataBinder;

import javax.sql.DataSource;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
@Configuration
@PropertySource("jdbc.properties")
@ComponentScan("tx.common")
public class DataSourceConfig {
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> type;


    @Bean
    public DataSource dataSource() {
        DataSource dataSource;
        try {
            dataSource = this.type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("创建DataSource失败", e);
        }

        DataBinder dataBinder = new DataBinder(dataSource);
        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.addPropertyValue("url", url);
        pvs.addPropertyValue("username", username);
        pvs.addPropertyValue("password", password);
        pvs.addPropertyValue("driverClassName", driverClassName);
        dataBinder.bind(pvs);
        return dataSource;
    }


    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
